/**
 * 修改用户数据接口
 */

//引入Q模块
let Q = require('q');

//updateProfile入口函数
let index = function(getData, postData, config, _redis, db) {
	redis = _redis;
	let deferred = Q.defer();
	if(postData.profileId && postData.profileVal) {
		let {profileId, profileVal} = postData;
		let userId;
		getUserId(postData._3rdSession).then(function(_userId) {
			userId = _userId;
			return db.connectDB('common');
		}, function() {
			//获取用户ID失败
			deferred.reject('-0081');
		}).then(function(commonDB) {
			let updateData = {};
			updateData[profileId] = profileVal;
			return commonDB.update('users', {
				userId: userId
			}, updateData);
		}, function() {
			//连接到公共数据库失败
			deferred.reject('-0127');
		}).then(function() {
			deferred.resolve(1);
		}, function() {
			//修改用户数据失败
			deferred.reject('-0198');
		});
	}
	else {
		//更改用户数据接口参数不足
		deferred.reject('-0197');
	}
	return deferred.promise;	
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		if(data) {
			data = JSON.parse(data);
			if(data.openId) {
				deferred.resolve(data.openId);
			}
			else {
				deferred.reject();
			}
		}
		else {
			deferred.reject();
		}
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};

